package com.vicene.gmail.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.vicene.gmail.auth.feign.MemberFeignService;
import com.vicene.gmail.auth.feign.ThirdPartFeignService;
import com.vicene.gmail.auth.vo.UserLoginVo;
import com.vicene.gmail.auth.vo.UserRegistVo;
import com.vicene.gmail.common.constant.AuthServerConstant;
import com.vicene.gmail.common.exception.CommonCodeEnum;
import com.vicene.gmail.common.utils.R;
import com.vicene.gmail.common.vo.WeiBoLoginResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/login.html")
    public String loginPage(HttpSession httpSession){
        Object attr = httpSession.getAttribute("sessionAttr:loginUser");
        if(attr == null){
            return "login";
        }
        return "redirect:http://gmail.com";
    }

    @GetMapping("/reg.html")
    public String regPage(){
        return "reg";
    }

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        phone = "13716364676";
        String redisCode=  redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACGE_PREFIX+ phone);
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - l < 60000){
                return R.error(CommonCodeEnum.SMS_CODE_EXCEPTION.getCode() ,CommonCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0 , 5);
        String smscode = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACGE_PREFIX  + phone, smscode , 60 , TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone  , code);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo , BindingResult result , RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().
                    collect(Collectors.toMap(fieldError -> {
                        return fieldError.getField();
                    }, fieldError -> {
                        return fieldError.getDefaultMessage();
                    }));
            redirectAttributes.addFlashAttribute("errors", errors);
            //model.addAttribute("errors" , errors);
            return "redirect:http://auth.gmail.com/reg.html";
        }

        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACGE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACGE_PREFIX + vo.getPhone());
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {

                    return "redirect:http://auth.gmail.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap();
                    errors.put("msg", (String) r.getData(new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gmail.com/reg.html";
                }
            }
            return "redirect:http://auth.gmail.com/reg.html";

        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gmail.com/reg.html";
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo vo ,  RedirectAttributes redirectAttributes , HttpSession session){
        R r =  memberFeignService.login(vo);

        if(r.getCode() == 0){
            session.setAttribute("loginUser" , r.getData(new TypeReference<WeiBoLoginResp>(){}));
            return "redirect:http://gmail.com";
        }else{
            Map<String,String> errors = new HashMap<>();
            errors.put("msg" , (String) r.getData("msg" , new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors" , errors);
            return "redirect:http://auth.gmail.com/login.html";

        }
    }


}
